<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问卷" prop="questionnaireId">
        <el-select v-model="queryParams.questionnaireId" placeholder="请选择问卷" clearable style="width: 240px" @change="handleQuestionnaireChange">
          <el-option v-for="item in questionnaireOptions" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="提交者" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入提交者姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="提交时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleExport" v-hasPermi="['questionnaire:answer:export']">导出数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['questionnaire:answer:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 恢复答卷表格和分页 -->
    <el-table v-loading="loading" :data="answerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="答卷编号" align="center" key="id" prop="id" v-if="columns[0].visible" width="80" />
      <el-table-column label="问卷标题" align="center" key="questionnaireTitle" prop="questionnaireTitle" v-if="columns[1].visible" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="提交者" align="center" key="userName" prop="userName" v-if="columns[2].visible" width="120" />
      <el-table-column label="提交者邮箱" align="center" key="userEmail" prop="userEmail" v-if="columns[3].visible" :show-overflow-tooltip="true" width="180" />
      <el-table-column label="提交者手机" align="center" key="userPhone" prop="userPhone" v-if="columns[4].visible" width="130" />
      <el-table-column label="提交时间" align="center" prop="submitTime" v-if="columns[5].visible" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" key="status" v-if="columns[6].visible" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === '1' ? '已提交' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['questionnaire:answer:query']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['questionnaire:answer:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 答卷详情对话框 -->
    <el-dialog title="答卷详情" v-model="detailOpen" width="800px" append-to-body>
      <div class="answer-detail" v-if="currentAnswer">
        <div class="answer-header">
          <h3>{{ currentAnswer.questionnaireTitle }}</h3>
          <p class="submitter-info">
            提交者：{{ currentAnswer.submitterName }} | 
            邮箱：{{ currentAnswer.submitterEmail }} | 
            手机：{{ currentAnswer.submitterPhone }} | 
            提交时间：{{ parseTime(currentAnswer.submitTime) }}
          </p>
        </div>
        <div class="answer-content">
          <div v-for="(detail, index) in currentAnswer.details" :key="detail.id" class="question-answer">
            <h4>{{ index + 1 }}. {{ detail.questionTitle }}</h4>
            <div class="answer-text">
              <span>{{ detail.optionLabel || '未填写' }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="QnQuestionnaireAnswer">
import { listAnswer, getAnswer, delAnswer, listQuestionnaire, getQuestionnaireStats } from "@/api/questionnaire"
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()

const answerList = ref([])
const questionnaireOptions = ref([])
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dateRange = ref([])
const currentAnswer = ref({})
const currentQuestionnaire = ref(null)

// 列显隐信息
const columns = ref([
  { key: 0, label: `答卷编号`, visible: true },
  { key: 1, label: `问卷标题`, visible: true },
  { key: 2, label: `提交者`, visible: true },
  { key: 3, label: `提交者邮箱`, visible: true },
  { key: 4, label: `提交者手机`, visible: true },
  { key: 5, label: `提交时间`, visible: true },
  { key: 6, label: `状态`, visible: true }
])

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    questionnaireId: undefined,
    userName: undefined
  }
})

const { queryParams } = toRefs(data)

/** 查询答卷列表 */
function getList() {
  loading.value = true
  const params = {
    ...queryParams.value,
    userName: queryParams.value.userName || undefined
  }
  listAnswer(proxy.addDateRange(params, dateRange.value)).then(res => {
    loading.value = false
    answerList.value = res.rows
    total.value = res.total
  })
}

/** 查询问卷选项 */
function getQuestionnaireOptions() {
  listQuestionnaire({ pageSize: 1000 }).then(res => {
    questionnaireOptions.value = res.rows
  })
}

/** 问卷变化处理 */
function handleQuestionnaireChange() {
  if (queryParams.value.questionnaireId) {
    getQuestionnaireStats(queryParams.value.questionnaireId).then(res => {
      // statsData.value = res.data // This line is removed
    })
    // 获取当前问卷信息
    const questionnaire = questionnaireOptions.value.find(q => q.id === queryParams.value.questionnaireId)
    currentQuestionnaire.value = questionnaire
  } else {
    currentQuestionnaire.value = null
    // statsData.value = { // This line is removed
    //   totalSubmissions: 0,
    //   todaySubmissions: 0,
    //   avgCompletionTime: 0,
    //   completionRate: 0
    // }
  }
  getList()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  currentQuestionnaire.value = null
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 查看详情按钮操作 */
function handleView(row) {
  const id = row.id
  getAnswer(id).then(response => {
    currentAnswer.value = response.data
    detailOpen.value = true
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const answerIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除答卷编号为"' + answerIds + '"的数据项？').then(function () {
    return delAnswer(answerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("questionnaire/answer/export", {
    ...queryParams.value,
  },`answer_${new Date().getTime()}.xlsx`)
}

getList()
getQuestionnaireOptions()
</script>

<style scoped>
.stats-card {
  text-align: center;
  padding: 20px;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #606266;
}

.answer-detail {
  padding: 20px;
}

.answer-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.answer-header h3 {
  color: #303133;
  margin-bottom: 10px;
}

.submitter-info {
  color: #606266;
  font-size: 14px;
}

.question-answer {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.question-answer h4 {
  color: #303133;
  margin-bottom: 10px;
}

.answer-text {
  color: #606266;
  line-height: 1.6;
}

.selected-options {
  margin-top: 5px;
}

.chart-container {
  padding: 20px;
}
</style> 